/**
 * Created by JetBrains WebStorm.
 * User: LXJ
 * Date: 11-8-8 下午4:57
 * Mail: louxiaojian@gmail.com
 */
if (!$.wanjuhe) {
    $.wanjuhe = {};
};
$.addCache=[];
$.add = function(o,fn,jq){
    if(typeof o != "string" || ($.addCache[o] && $.addCache[o].has)) return false;
    var st = o.toString().split('.'),stLength = st.length,dc,d= jq || $.wanjuhe;
    $.each($(st),function(i,v){
        if(!d[this]){
            d[this] = i == (stLength-1) ? fn : {};
        };
        dc = d;
        d = d[this];
    });
    $.addCache[o] = {};
    $.addCache[o].has = 1;
    if($.isFunction(d)){
        $.addCache[o].use = function(){d.call(dc)};
    };
};
$.use = function(o,fn){
    if(!$.addCache[o]){
        $.add(o,fn);
    };
    $.addCache[o].use && $.addCache[o].use();
};
if(!Array.prototype.indexOf){
    Array.prototype.indexOf = function(val) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] == val) return i;
        }
        return -1;
    };
};
Array.prototype.remove = function(val) {
    var index;
    while((index=this.indexOf(val)) > -1){
        this.splice(index,1);
    };
};
Array.prototype.distinct = function(){
    var self = this,_a = this.concat().sort();
    _a.sort(function(a,b){
        if(a == b){
            var n = self.indexOf(a);
            self.splice(n,1);
        }
        return 0;
    });
    return self;
};
$.add("parse_config",function(str){
    var cache={},str = str.toString();
    str = /\?/.test(str) ? str.split(/\?+/)[1] : str;
    str.replace(/[?&]*((?:(?!=)(?!\?).)*)=*((?:(?!&)(?!\?).)*)/ig,function(k0,key,value){
        if(key){
            cache[key] = value;
        }
    });
    return cache;
},jQuery);
function trim(str,undef){
   var EMPTY = '',
    _trim = String.prototype.trim,
    RE_TRIM = /^\s+|\s+$/g,
    strtrim=_trim ?  ((str == undef) ? EMPTY : _trim.call(str)) : ((str == undef) ? EMPTY : str.toString().replace(RE_TRIM, EMPTY));
    return strtrim;
};
function cutstr(str, end){
    var str = trim(str.toString()),d = 0,str_cut = "", strLen = str.length;
    for (var f = 0; f < strLen; f++){
        d = str.charCodeAt(f) > 255 ? d+2 : d+1;
//        str_cut += str[f]; 在IE6,7下存在bug，str[f]在IE6,7下值为undefind
        str_cut += str.charAt(f);
        if (d >= end) return str_cut += "...";
    };
    if (d < end) return str;
};
jQuery(function($){
    $.use('search',function(){
        var input=$('#tsText'),
            topSearch = $('.topSearch'),
            suggestContent = $('#J_Suggest-content');
        input.keyup(function(){
            var inputValue = $(this).val().toString();
            if(!trim(inputValue)) {
                suggestContent.hide();
                return false;
            };
            suggestContent.show();
            $('.suggest-key').html(cutstr(inputValue,10));
        });
        topSearch.delegate('.suggest-item','mouseenter',function(){
            var value =  $(this).attr('data-value');
            if(value){
                $('#searchType').val(value);
                $('#filter').val({"1":"goods","2":"house","3":"user"}[value] || "goods");
            };
        }).delegate('.suggest-item,.sBtn','click',function(){
                input[0].form.submit();
                return false;
        });
        $(document).mouseup(function(){suggestContent.hide();})
    });
    $.use('delegateEvent',function(){
        $(document).delegate('[data-type]','click',function(){
            var _this = $(this),dataType = _this.attr('data-type');
            ;({
                "dialog-login" : function(){
                    $('#login').dialog({width:'800px',dragKey:'1',dialogClass : 'wjh-test'});
                },
                "dialog-reg" : function(){
                    $('#reg').dialog({width:'800px',dragKey:'1'});
                },
                "simulate-select" : function(){
                    _this.simulateSelect({"offsetParent":".dialog","adjustY":-1,"adjustLayerWidth":-2});
                },
                "backTop" : function(){
                    scrollTo(document.documentElement.scrollTop || document.body.scrollTop,0);
                }
            }[dataType] || function(){})();
            return false;
        });
        $(document).delegate('[data-type=simulate-select-hover]','mouseenter',function(){
            $(this).simulateSelect({"offsetParent":".dialog","adjustY":-1,"adjustLayerWidth":-2,"eventType":'mouseover'});
        })
    });
    $.use('Rotation',function(){
        var S = $.wanjuhe;
        S.$$ = function(node, name, type) {
            var r = [], re = new RegExp("(^|\\s)" + name + "(\\s|$)"), e = (node || document).getElementsByTagName(type || "*");
            for ( var i = 0,len=e.length; i < len; i++ ) {
                if(re.test(e[i].className) )
                    r.push(e[i]);
            }
            return r;
        };
        S.parse_config = function(str){
            var pa={};
            str.replace(/[?&]*((?:(?!=).)*)=*((?:(?!&)(?!\?).)*)/ig,function(k0,k1,k2){
                if(k1){
                    pa[k1] = k2;
                }
            });
            return pa;
        };
        S.initFun = function(str){
            var str = new String(str),strTOa = str.split('.'),curContent = window;
            for(var i = 0;i<strTOa.length;i++){
                if(!curContent[strTOa[i]]){
                    curContent = false;
                    break;
                }
                curContent = curContent[strTOa[i]];
            };
            return curContent;
        };
        Rotation.rotationLayout = {
            trigger :function(plugRotation,mTag){
                var items = mTag,
                    trigger_before = '<ul class="rotation-trigger">',
                    trigger_after = '</ul>',
                    trigger_item_befor = '<li class="trigger-item"><span class="sp"><a href="{{href}}">',
                    trigger_item_after = '</a></span></li>',
                    div = document.createElement('div'),
                    elemStr =[trigger_before];
                for(var i=0,ien = items.length;i<ien;i++){
                    var item=items[i],
                        alink=item.getElementsByTagName('a')[0],
                        title=alink.title,
                        href=alink.href;
                    elemStr.push((trigger_item_befor+(i+1)+trigger_item_after).replace(/\s*\{\{href\}\}\s*/,href));
                };
                elemStr.push(trigger_after);
                div.innerHTML = elemStr.join('');
                plugRotation.appendChild(div.firstChild);
                return S.$$(plugRotation,'trigger-item','*');
            },
            text : function(plugRotation,mTag){
                var items = mTag,
                    text_before='<ul class="text-trigger">',
                    text_after = '</ul>',
                    text_item_befor = '<li class="tt-item"><a href="{{href}}">',
                    text_item_after = '</a></li>',
                    textStr=[text_before],
                    div = document.createElement('div');
                for(var i=0,ien = items.length;i<ien;i++){
                    var item=items[i],
                        alink=item.getElementsByTagName('a')[0],
                        title=alink.title,
                        href=alink.href;
                    textStr.push((text_item_befor+title+text_item_after).replace(/\s*\{\{href\}\}\s*/,href));
                };
                textStr.push(text_after);
                div.innerHTML = textStr.join('');
                plugRotation.appendChild(div.firstChild);
                return S.$$(plugRotation,'tt-item','*');
            }
        };

        /**
         *选项卡根据html中包含类名plug-tab进行统一初始化，初始化时参数由html自定义属性data-tab-config设置，传递的参数类型为url传参数类型
         * 实例：data-rotation-config = 'evt=1&auto=3000&dis=235&dir=left&rotationInitBack=lxj';
         * @auto 整数 选项卡自动播放时的时间间隔
         * @dis 整数 选项卡每次滑动效果时的滑动距离.
         * @dir left or top 水平滑动或是垂直滑动.
         * @rotationInitBack 初始化选项卡之前执行的函数(用来动态创建选项卡所需要的结构如：触发按钮或是显示文字)
         */

        Rotation.rotationInit = function(){
            var plugRotations= S.$$(document,'plug-rotation','*');
            if(plugRotations.length == 0){
                return false;
            };
            for(var i= 0,ien=plugRotations.length;i<ien;i++){
                var plugRotation=plugRotations[i],
                    data_rotation_config=plugRotation.getAttribute('data-rotation-config'),
                    config=data_rotation_config ? S.parse_config(data_rotation_config) : {},
                    rotation_panels = S.$$(plugRotation,'rotation-panel','*'),
                    rotation_panel = rotation_panels[0],
                    nTag,
                    text;
                mTag = S.$$(plugRotation,config.rpSelector || 'rp-item','*');
                mTag.length > 0 && (config.mTag =  mTag);

                nTag = S.$$(plugRotation,config.triggerSelector || 'trigger-item','*');
                if(nTag.length == 0){
                    config.trigger && (nTag = typeof S.initFun(config.trigger) == "function" ?  S.initFun(config.trigger)(plugRotation,mTag) : Rotation.rotationLayout.trigger(plugRotation,mTag));
                }
                config.nTag = nTag && nTag.length > 0 && (config.nTag = nTag);

                text = S.$$(plugRotation,'tt-item','*');
                if(text.length == 0){
                    config.text && (text = typeof S.initFun(config.text) == "function" ?  S.initFun(config.text)(plugRotation,mTag) : Rotation.rotationLayout.text(plugRotation,mTag));
                }
                config.text = text && text.length > 0 && (config.text = text);

                if(config.dis){
                    config.slider={};
                    config.slider.dis = config.dis;
                    config.slider.dir = config.dir;
                    config.slider.obj = rotation_panel;
                };
                config.auto && (config.auto = [1,config.auto]);
                var nr = new Rotation(config);
                config.rotationInitBack && S.initFun(config.rotationInitBack).call(nr,config);
            }
        }();
    });
    $.add('waterfall',function(config){
        if(!$('#J_waterfall-contenter')[0]) return false;
        var waterfall_contenter = $('#J_waterfall-contenter'),
            loading = waterfall_contenter[0].loading,
            wjh_waterfall = $('#J_waterfall-contenter .item').waterfall($.extend({
                "contenter" : '#J_waterfall-contenter',
                "spaceLevel" : '14',
                "itemWidth" : "230px",
                'elemsAdjust':function(){
                    var self=this,
                        cols = this.cols,
                        cssHeight = this.cssHeight,
                        cssWidth = this.cssWidth,
                        itemWidth = parseInt(this.config.itemWidth),
                        spaceLevel = parseInt(this.spaceLevel);
                    ;({
                        "index-bd" : function(){
                            var user_nfo = $('#J_user-info'),
                                J_attention = $('#J_attention'),
                                noContent = $('.no-content');
                            self.addItem(1,1,user_nfo);
                            self.addItem(2,1,J_attention);
                            if(noContent){
                                noContent.css({"margin-left":cssWidth[1],"visibility":"visible"});
                            };
                        },
                        "house-index-bd" : function(){
                            var J_filter = $('#J_filter');
                            J_filter[0] && self.addItem(1,1,J_filter);
                            $('.wjh-tab-wrap').css({"width":cols*(itemWidth+spaceLevel)-spaceLevel+'px'});
                        },
                        "chuanmen-bd" : function(){
                            var homeRank = $('#home-rank');
                            homeRank && self.addItem(1,'last',homeRank);
                            $('.st-wrap').css({"width":cols*(itemWidth+spaceLevel)-spaceLevel+'px'});
                        },
                        "list-bd" : function(){
                            var cat_list = $('#cat-list'),
                                spaceVertical = self.spaceVertical,
                                h = cssHeight.concat(),
                                crumb = $('.crumb'),
                                crumbHeight = 0,
                                selectFfilter = $('.select-filter'),
                                selectFfilterHeight = 0,
                                homeRank = $('#home-rank');
                            self.addItem(1,1,cat_list);
                            self.addItem(1,'last',homeRank);
                            if(crumb[0]){
                                crumb.css({"width":(cols-1)*(itemWidth+spaceLevel)-spaceLevel-2+'px'});
                                crumbHeight = crumb.outerHeight()+self.spaceVertical;
                            }
                            if(selectFfilter[0]){
                                selectFfilter.css({"width":(cols-1)*(itemWidth+spaceLevel)-spaceLevel+'px'});
                                selectFfilterHeight = selectFfilter.outerHeight()+self.spaceVertical;
                            };
                            if(h.sort(function(a,b){return parseInt(a) > parseInt(b) ? -1 : 1})[0]==0){
                                $.each(h,function(index){
                                    if(index > 0){
                                        self.cssHeight[index]=crumbHeight+selectFfilterHeight;
                                    };
                                });
                                crumb.css({"top":cssHeight[0],"left":cssWidth[1],"visibility":"visible"});
                                selectFfilter.css({"top":cssHeight[0]+crumb.outerHeight()+spaceVertical,"left":cssWidth[1],"visibility":"visible"})
                            };
                        }
                    }[$('body').attr('id')] || function(){})();
                },
                'itemBack':function(){
                    this.css({'visibility':'visible'})
                }
            },config || {}));
        if(!loading){
            loading = $('<div class="loading">加载中.........</div>').hide().appendTo(waterfall_contenter.parent());
        };
        return { "wjh_waterfall":wjh_waterfall,"loading":loading,"waterfall_contenter" :waterfall_contenter};
    });
    $.use('wjh_item_hover',function(){
        if($.browser.msie && $.browser.version == "6.0"){
            $(document).delegate('.wjh-item','mouseover',function(){
                $(this).addClass("wjh-item-hover");
            });
            $(document).delegate('.wjh-item','mouseout',function(){
                $(this).removeClass("wjh-item-hover");
            });
            $(document).delegate('.wjh-item .thumb-outer','mouseover',function(){
                $(this).addClass("thumb-outer-hover");
            });
            $(document).delegate('.wjh-item .thumb-outer','mouseout',function(){
                $(this).removeClass("thumb-outer-hover");
            });
        }
    });
    $.use('backTop',function(){
        var backTop = $('.backTop');
        backTop[0] && $(window).scroll(function(){
            $(document).scrollTop() > 0 ? backTop.show() : backTop.hide();
        });
    });
});
